import cv2
import numpy as np
if __name__ == '__main__':
    # 1. 图片输入
    image_np = cv2.imread("C:\\Users\\20436\Desktop\zuqiu.jpg")
    # 2. 模板输入
    template = cv2.imread("C:\\Users\\20436\Desktop\moban.jpg")
    h = template.shape[0]
    w = template.shape[1]
    # 3. 模板匹配
    res = cv2.matchTemplate(
        image_np,  # 原始图像
        template,  # 模板
        cv2.TM_CCOEFF_NORMED  # 归一化相关系数匹配
    )
    threshold = 0.80

    # 小于阈值的就是匹配成功
    loc = np.where(res > threshold)

    # 4. 绘制轮廓
    for x, y in zip(loc[1], loc[0]):
        print('坐标：', (x, y))
        # 画框
        cv2.rectangle(
            image_np,
            (x, y),
            (x + w, y + h),  # 右下角是左上角加上模板的宽高
            (0, 0, 255),
            thickness=2
        )

    # 5. 图片输出
    cv2.imshow('contour_image', image_np)
    cv2.imwrite('contour_image.jpg',image_np)
    cv2.waitKey(0)


